package com.gl.order.commom.excetion;

import cn.hutool.core.collection.CollUtil;
import com.gl.order.commom.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: liangSY
 * @Date: 2021/6/21
 * @ClassName: GlobalExceptionHandler
 * @Description: 异常处理（全局）
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResultBean exceptionHandler(Exception e) {
        log.error(e.getMessage(),e);
        return ResultBean.failed(e.getMessage());
    }

    @ExceptionHandler(value = ServiceExcetion.class)
    public ResultBean ServiceExcetionHanle(ServiceExcetion e) {
        log.error(e.getMessage(),e);
        return ResultBean.failed(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultBean handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        String msg = null;
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        if (!CollUtil.isEmpty(fieldErrors)) {
            log.error(e.getMessage(), e);
            msg = fieldErrors.get(0).getDefaultMessage();
        }
        return ResultBean.failed(msg);
    }
}
